// @flow
import React, { Component } from 'react'
import styles from './MenusAdd.css'
import { Form, Input, Button, message, TreeSelect } from 'antd'
import universalFetch, { handleFetchError } from 'store/modules/fetch'
const FormItem = Form.Item
const SHOW_PARENT = TreeSelect.SHOW_PARENT
const formItemLayout = {
  labelCol: {
    xs: { span: 24 },
    sm: { span: 6 }
  },
  wrapperCol: {
    xs: { span: 24 },
    sm: { span: 14 }
  }
}

const tailFormItemLayout = {
  wrapperCol: {
    xs: {
      span: 24,
      offset: 0
    },
    sm: {
      span: 14,
      offset: 6
    }
  }
}
type Props = {
  form: Object,
  history: Object
}

type States = {
  loading: boolean,
  menus: Array<Object>,
  taskData: Object,
  value: Array<Object>
}
class FaultInfoEdit extends Component {
  props: Props
  state: States
  submit: Function
  goBack: Function
  initChildren: Function
  getMenus: Function
  constructor (props: Props) {
    super(props)
    this.state = {
      loading: false,
      value: [],
      taskData: {},
      menus: []
    }
    this.submit = this.submit.bind(this)
    this.goBack = this.goBack.bind(this)
    this.getMenus = this.getMenus.bind(this)
    this.onChange = this.onChange.bind(this)
  }

  componentWillMount () {
    this.getMenus()
    const { data } = this.props.history.location.state
    this.setState({
      taskData: data,
      value: data.parentId
    })
  }

  submit () {
    const { form } = this.props
    form.validateFields((err, fieldsValue) => {
      if (err) {
        return false
      }
      this.setState({
        loading: true
      })
      const values = {
        ...fieldsValue
      }
      const { taskData } = this.state
      universalFetch(`${__SERVICE_API__}device/fault/${taskData.id}`, {
        method: 'PUT',
        headers: {
          'Content-Type': 'application/json',
          'Accept': 'application/json'
        },
        body: JSON.stringify(values)
      })
        .then(res => res.json())
        .then((json) => {
          if (json.code !== 200000) {
            throw new Error(JSON.stringify({ code: json.code, message: json.message }))
          }
          this.setState({
            loading: false
          })
          message.success('修改成功')
          this.props.history.push('/business/faultInfo')
        })
        .catch((error) => {
          handleFetchError(error)
          console.error(error)
          message.error('修改失败')
          this.setState({
            loading: false
          })
        })
    })
  }

  goBack () {
    this.props.history.push('/business/faultInfo')
  }
  onChange = (value) => {
    this.setState({ value: value })
  }
  initChildren (object) {
    const children = object.children.map((data, index) => {
      let data1 = {}
      data1['key'] = object.key + '-' + index + ''
      data1['value'] = data.id + ''
      data1['label'] = data.faultName + ''
      data1['children'] = data.children
      this.initChildren(data1)
      return data1
    })
    object['children'] = children
  }
  getMenus () {
    universalFetch(`${__SERVICE_API__}device/fault/faults?isTree=true`)
      .then((res) => res.json())
      .then((json) => {
        if (json.code !== 200000) {
          throw new Error(JSON.stringify({ code: json.code, message: json.message }))
        }
        this.setState({
          menus:json.result.map((data, index) => {
            let data1 = {}
            data1['key'] = '0' + '-' + index + ''
            data1['value'] = data.id + ''
            data1['label'] = data.faultName + ''
            data1['children'] = data.children
            this.initChildren(data1)
            return data1
          })
        })
      })
      .catch((error) => {
        handleFetchError(error)
        console.error(error)
      })
  }
  render () {
    const { getFieldDecorator } = this.props.form
    const { loading, menus, value, taskData } = this.state
    const tProps = {
      treeData: menus,
      value: value,
      onChange: this.onChange,
      multiple: false,
      treeCheckable: false,
      treeDefaultExpandAll: true,
      showCheckedStrategy: SHOW_PARENT,
      placeholder: '请选择父类故障',
      searchPlaceholder: 'Please select',
      style: {
        width: 300
      }
    }
    return (
      <div className={styles['main']}>
        <Form>
          <FormItem {...formItemLayout} label='故障归类' hasFeedback>
            {
              getFieldDecorator('parentId', {
                initialValue: taskData.parentId.toString(),
                rules: [
                  { required: true, message: '请选择', whitespace: true }
                ]
              })(
                <TreeSelect {...tProps} />
              )
            }
          </FormItem>
          <FormItem {...formItemLayout} label='故障类别' hasFeedback>
            {
              getFieldDecorator('faultName', {
                rules: [
                  { required: true, message: '请填写故障类别', whitespace: true }
                ],
                initialValue: taskData.faultName
              })(
                <Input placeholder='请填写故障类别' />
              )
            }
          </FormItem>
          <FormItem {...formItemLayout} label='故障代码' hasFeedback>
            {
              getFieldDecorator('faultCode', {
                rules: [
                  { required: true, message: '请填写故障代码', whitespace: true }
                ],
                initialValue: taskData.faultCode
              })(
                <Input placeholder='请填写故障代码' />
              )
            }
          </FormItem>
          <FormItem {...formItemLayout} label='描述' hasFeedback>
            {
              getFieldDecorator('faultDesc', {
                rules: [
                  { required: true, message: '请填写描述信息', whitespace: true }
                ],
                initialValue: taskData.faultDesc
              })(
                <Input placeholder='请填写' type='textarea' autosize={{ minRows: 1, maxRows: 30 }} />
              )
            }
          </FormItem>
          <FormItem {...tailFormItemLayout}>
            <Button type='primary'
              loading={loading}
              onClick={this.submit}
              >
              保存
            </Button>
            <Button
              onClick={this.goBack}
              style={{ marginLeft: '20px' }}
              >
              返回
            </Button>
          </FormItem>
        </Form>
      </div>
    )
  }
}

export default Form.create()(FaultInfoEdit)
